﻿using IM.Easy.Core.AppContext;
using IM.Easy.Core.Extensions;
using IM.Easy.Core.Security;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Entity.System;
using IM.Easy.Infrastructure.Query;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.Dtos.User;
using IM.Easy.SystemServices.IServices;
using Mapster;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.SystemServices.Services
{
    public class UserProfileService(ISqlSugarClient db) : AppServices<SysUser>(db), IUserProfileService
    {

        /// <summary>
        /// 获取账户基本资料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UserProfile Get(long id)
        {
            var user = Context.Queryable<SysUser>()
                        .Includes(s => s.Department)
                        .Includes(s => s.Roles)
                        .InSingle(id);
            var profile = user.Adapt<UserProfile>();

            return profile;
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="dto">密码修改传输对象</param>
        public void UpdatePassword(PasswordDto dto)
        {
            // 验证数据有效性
            if (dto == null)
                throw new ArgumentNullException(nameof(dto), "密码修改数据不能为空");

            var userId = ImApp.User.Id;

            // 查询用户
            var user = GetById(userId);
            if (user == null)
                ExceptionUtils.ThrowBusinessException("用户不存在");

            // 验证当前密码
            if (!VerifyPassword(dto.OldPassword, user.Password))
                ExceptionUtils.ThrowBusinessException("当前密码不正确");

            // 更新密码
            user.Password = Sha256Hash.ComputeHash(dto.NewPassword); // 使用加密后的新密码

            // 保存修改
            Context.Updateable(user)
                    .UpdateColumns(s => s.Password)
                    .ExecuteCommandHasChange();
        }

        /// <summary>
        /// 验证密码
        /// </summary>
        /// <param name="inputPassword">用户输入的密码</param>
        /// <param name="storedPassword">数据库中存储的加密密码</param>
        /// <returns>是否验证成功</returns>
        private bool VerifyPassword(string inputPassword, string storedPassword)
        {
            // 假设使用了SHA256或类似加密方式存储密码
            var hashedInput = Sha256Hash.ComputeHash(inputPassword);
            return hashedInput == storedPassword;
        }

        /// <summary>
        /// 更新头像
        /// </summary>
        /// <param name="avatar"></param>
        /// <returns></returns>
        public void UpdateAvatar(string avatar)
        {
            var userId = ImApp.User.Id;
            var user = GetById(userId);
            user.Avatar = avatar;
            Context.Updateable(user)
                 .UpdateColumns(s => s.Avatar)
                 .ExecuteCommandHasChange();
        }
    }
}
